package com.kettle.job;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.repository.filerep.KettleFileRepository;
import org.pentaho.di.repository.filerep.KettleFileRepositoryMeta;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.springframework.beans.factory.annotation.Autowired;

import com.kettle.model.datalog.Datalog;
import com.kettle.model.kettle.Kettlemap;
import com.kettle.model.kettle.Kettlework;
import com.kettle.service.datalog.DatalogService;
import com.kettle.service.kettle.KettleService;
import com.kettle.service.kettle.KettlesendService;
import org.springframework.beans.factory.annotation.Value;

/**
 * Job任务
 */
public class QuyartzJob implements Job {
	
	@Autowired
	private KettleService kettleService;
	
	@Autowired
	private KettlesendService kettlesendService;
	
	@Autowired
	private DatalogService datalogService;

	@Value("${kettlepath.lnurlpath}")
	private String lnurlpath;

	@Value("${kettlepath.lnmfilepath}")
	private String lnmfilepath;
	
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
    	//JobDataMap map = context.getJobDetail().getJobDataMap();//获取传递参数
        System.out.println("----hello world---" + new Date());
        JobKey key = context.getJobDetail().getKey();
        String jobname=key.getName();
        String jobgroupname=key.getGroup();
        //String mClassPath = Thread.currentThread().getContextClassLoader().getResource("/").toString();
        Datalog kmap=new Datalog();
		String uuid = UUID.randomUUID().toString();
		uuid = uuid.replace("-", "");
		kmap.setId(uuid);
		kmap.setJobname(jobname);
		kmap.setJobgroupname(jobgroupname);
		
		Map<String,Object> pastmap=new HashMap<String,Object>();      
		pastmap.put("jobname", jobname);
		pastmap.put("jobgroupname", jobgroupname);
		List<Kettlework> mapid=kettleService.listByMap(pastmap);
		String kid=mapid.size() > 0 ? mapid.get(0).getId() : "";
		
		String filepath="";
		if(!"".equals(kid)) {
			filepath= mapid.get(0).getFilepath();
		}
		
		kmap.setLxdm("1");
		kmap.setZxlb("1");
		Timestamp start = new Timestamp(System.currentTimeMillis());
		Kettlework kwork=new Kettlework();
		kwork.setId(kid);
		kwork.setCzzt("3");
		kwork.updateById();//初始更新为3,正在执行
        try {			
			//String kfile=SysUtils.pcurlpath+SysUtils.pcmfilepath;
        	String kfile=lnurlpath+lnmfilepath;
        	if(!KettleEnvironment.isInitialized()){
				// Kettle初始化需要修改相应的配置路径  
				System.setProperty( "java.naming.factory.initial", "org.osjava.sj.SimpleContextFactory" );
        		//System.setProperty("java.naming.factory.initial","weblogic.jndi.WLInitialContextFactory");
				System.setProperty("user.dir",kfile);
				System.setProperty("KETTLE_HOME",kfile);
				KettleEnvironment.init(false);
			}	
			// 资源库元对象
			KettleFileRepositoryMeta repinfo = new KettleFileRepositoryMeta("kettle","kettle","数据采集",kfile);
			// 文件形式的资源库
			KettleFileRepository repository = new KettleFileRepository();
			repository.init(repinfo);
			Timestamp startw = new Timestamp(System.currentTimeMillis());
			filepath="";//默认为空时不影响之前, 后期升级需要开启
			pastmap.put("filepath","".equals(filepath)?"/":"/"+filepath);
			Kettlemap kstr=kettlesendService.execJob(repository,jobname,filepath, pastmap, null);
			Timestamp end = new Timestamp(new Date().getTime()); 
			String czzt=kstr.isSuccess()?"1":"2";
			kmap.setKssj(startw);
			kmap.setJssj(end);
			kmap.setCzzt(czzt);
			kmap.setZxbz(kstr.getZxbzlog());
			kmap.setLogs(kstr.getLogs());
			//System.out.println(JSON.toJSONString(kstr));
		} catch (KettleException e) {
			e.printStackTrace();
			System.out.println("出现异常"+e.getMessage());
			JobExecutionException e2 = new JobExecutionException(e);
			//自动停止job相关的触发器，job停止
			e2.setUnscheduleAllTriggers(true);
            //自动任务报错继续执行
			//e2.setRefireImmediately(true);
			Timestamp end = new Timestamp(new Date().getTime()); 
			kmap.setKssj(start);
			kmap.setJssj(end);
			kmap.setCzzt("2");
			kmap.setZxbz("出现异常");
			kmap.setLogs(e.getMessage()==null?"出现异常":e.getMessage());
		}finally{
			datalogService.save(kmap);
			kwork.setKssj(kmap.getKssj());
			kwork.setJssj(kmap.getJssj());
			kwork.setCzzt(kmap.getCzzt());
			kettleService.updateById(kwork);
		}
    }

}
